<template>
  <div>
    <!--面包屑导航区-->
    <div style="padding:24px;">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--卡片视图区-->
    <el-card class="box-card">
      <!--搜索与添加区-->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input placeholder="请输入内容" clearable @clear="getUserList()" v-model="queryInfo.query" class="input-with-select">
            <el-button slot="append" @click="getUserList()" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!--表格区-->
    <el-table :data="userList" border stripe>
      <el-table-column label="#" type="index"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="create_time" label="时间"></el-table-column>
      <el-table-column prop="mg_state" label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="editFormUser(scope.row.id)"></el-button>
          <el-button size="mini" type="danger" icon="el-icon-remove" @click="delUser(scope.row.id)"></el-button>
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable=false>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="asignRoleDialog(scope.row.id)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <!--添加用户对话框-->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="closeAddDialog()">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑用户对话框-->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="closeEditDialog()">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="角色分配" :visible.sync="assignRoleDialogVisible" width="50%" @close="closeAssignRoleDialog()">
      <el-table :data="roleList" border stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignRoleDialogVisible = false">取 消</el-button>
        <el-button @click="assignRole()" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  userList,
  addUser,
  loadUser,
  delUser,
  changeState,
  roleList,
} from "@/request/api";
import { ElForm } from "element-ui/types/form";
import Vue from "vue";
import Component from "vue-class-component";
import { Ref } from "vue-property-decorator";
interface rulesType {
  required: boolean;
  message: string;
  trigger: string;
}
interface rulesType2 {
  min: number;
  max: number;
  message: string;
  trigger: string;
}
interface rulesType3 {
  validator: Function;
  trigger: string;
}
@Component
export default class User extends Vue {
  queryInfo: {
    query: string;
    pagenum: number;
    pagesize: number;
  } = {
    query: "",
    pagenum: 1,
    pagesize: 5,
  }; // 查询条件
  userList: Array<any> = []; // 用户列表
  total: number = 0; // 数据总数
  addDialogVisible: boolean = false; // 添加对话框
  addForm: {
    username: string;
    password: string;
    email: string;
    mobile: string;
  } = {
    username: "",
    password: "",
    email: "",
    mobile: "",
  }; // 添加用户信息
  addFormRules: {
    username: Array<rulesType | rulesType2>;
    password: Array<rulesType | rulesType2>;
    email: Array<rulesType | rulesType3>;
    mobile: Array<rulesType | rulesType3>;
  } = {
    username: [
      { required: true, message: "请输入用户名", trigger: "blur" },
      { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
    ],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      { min: 6, max: 12, message: "长度在 6 到 12 个字符", trigger: "blur" },
    ],
    email: [
      { required: true, message: "请输入邮箱", trigger: "blur" },
      { validator: this.volidateEmail, trigger: "blur" },
    ],
    mobile: [
      { required: true, message: "请输入手机号", trigger: "blur" },
      { validator: this.volidatePhone, trigger: "blur" },
    ],
  }; // 添加用户规则
  editDialogVisible: boolean = false; // 编辑对话框
  editForm: {
    email: string;
    id: number;
    mobile: string;
    rid: number;
    username: string;
  } = {
    email: "",
    id: 0,
    mobile: "",
    rid: 0,
    username: "",
  }; // 编辑用户信息
  editFormRules: {
    email: Array<rulesType | rulesType3>;
    mobile: Array<rulesType | rulesType3>;
  } = {
    email: [
      { required: true, message: "请输入邮箱", trigger: "blur" },
      { validator: this.volidateEmail, trigger: "blur" },
    ],
    mobile: [
      { required: true, message: "请输入手机号", trigger: "blur" },
      { validator: this.volidatePhone, trigger: "blur" },
    ],
  }; // 编辑用户规则
  assignRoleDialogVisible: boolean = false; // 授权对话框
  roleList: Array<any> = []; // 角色列表
  volidateEmail(rule: any, value: string, callback: Function) {
    var regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    if (regEmail.test(value)) {
      callback();
    }
    callback(new Error("请输入合法的邮箱"));
  }
  volidatePhone(rule: any, value: string, callback: Function) {
    var regPhone = /^1[3456789]\d{9}$/;
    if (regPhone.test(value)) {
      callback();
    }
    callback(new Error("请输入正确的手机号格式"));
  }
  created() {
    this.getUserList();
  }
  handleSizeChange(size: number) {
    this.queryInfo.pagesize = size;
    this.getUserList();
  }
  handleCurrentChange(currentPage: number) {
    this.queryInfo.pagenum = currentPage;
    this.getUserList();
  }
  async getUserList() {
    const { data, meta } = await userList(this.queryInfo);
    if (meta.status !== 200) {
      this.$message.error("用户列表获取失败");
    }
    // console.log(data);
    this.userList = data.users;
    this.total = data.total;
  }
  @Ref("addFormRef") addFormRef!: ElForm;
  addUser() {
    this.addFormRef.validate(async (valid: boolean) => {
      if (!valid) return;
      let { data, meta } = await addUser(this.addForm);
      if (meta.status !== 201) {
        this.$message.error("添加用户失败");
        return;
      }
      this.$message.success("添加用户成功");
      // 关闭对话框
      this.addDialogVisible = false;
      // 刷新表格数据
      this.getUserList();
    });
  }
  closeAddDialog() {
    this.addFormRef.resetFields();
  }
  // 加载用户
  async editFormUser(id: number) {
    const { data, meta } = await loadUser(id);
    if (meta.status !== 200) {
      return this.$message.error("获取用户失败");
    }
    console.log(data);
    this.editForm = data;
    this.editDialogVisible = true;
  }
  // 删除
  async delUser(id: number) {
    const confirmRes = await this.$confirm(
      "此操作将永久删除该用户, 是否继续?",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    ).catch((err) => {
      return err;
    });
    if (confirmRes !== "confirm") {
      return this.$message.warning("取消了删除操作");
    }
    // 删除用户
    const { data, meta } = await delUser(id);
    if (meta.status !== 200) {
      return this.$message.error("删除用户失败");
    }
    // 提示删除成功
    this.$message.success("删除用户成功");
    // 刷新表格
    this.getUserList();
  }
  async changeState(row: {
    create_time: number;
    email: string;
    id: number;
    mg_state: boolean;
    mobile: string;
    role_name: string;
    username: string;
  }) {
    const { data, meta } = await changeState(row.id, row.mg_state);
    if (meta.status === 200) {
      this.$message.success(meta.msg);
    } else {
      this.$message.error("设置失败");
      row.mg_state = !row.mg_state;
    }
  }

  userid: number = 0;
  async asignRoleDialog(id: number) {
    // 查询所有的角色
    const { data, meta } = await roleList();
    if (meta.status === 200) {
      this.assignRoleDialogVisible = true;
      this.roleList = data;
      this.userid = id;
    }
  }
  // 关闭分配角色对话框
  closeAssignRoleDialog() {
    this.assignRoleDialogVisible = false;
  }
  // 分配角色功能
  assignRole() {
    // var userid = this.userid
  }
}
</script>

<style lang="less" scoped>
</style>